import React, { Component } from 'react'
import loanAndRefundService from "./loan-and-refund.service";
import AdvancedTable from "components/advanced-table";
import Info from "components/info";
import { messages, queryCurrencyPrecision } from "share/common";
import moment from "moment";
import { Badge, Popover, Modal, message } from "antd";
import httpFetch from "share/httpFetch";
import SlideFrame from "components/slide-frame";
import ViewLine from "containers/loan-billing/template/view-line";
import openSlideFrame from "share/openSlideFrame";
import ViewHistory from "containers/loan-billing/template/view-history";
import RepaymentDetailFrame from 'containers/loan-billing/template/refund-content'
import TransactionModal from "containers/loan-billing/template/transaction-modal";
import repaymentContent from "containers/loan-billing/template/repayment-content";
import { connect } from "react-redux";
import ListSelector from "components/list-selector";

@connect(mapStateToProps)
class SubList extends Component {

  state = {
    loading: false,
    loanInfo: {},
    historyModal: false,
    historyId: '',
    editRecord: {},
    tableLoading: false,
    sort: ''
  };

  componentDidMount() {
    this.getEmployeeLoanInfo();
  }

  getEmployeeLoanInfo = () => {
    const { payeeId, currencyCode, companyOID } = this.props.location.state;
    this.setState({ loading: true });
    loanAndRefundService.getLoanInfoByEmployeeId(payeeId, currencyCode, companyOID).then(res => {
      this.setState({ loanInfo: res.data || {}, loading: false })
    })
  };

  attributes = loanInfo => (
    [
      {
        title: loanInfo.payeeType === 1002 ? messages('finance-1.key19')/*员工*/: messages('finance-1.key20')/*供应商*/,
        dataIndex: 'payeeName', span: 24,
        render: (value, record) => (
          <span>
            {
              loanInfo.payeeType === 1002
                ? `${record.payeeName}(${record.employeeId})`
                : `${record.payeeName}(${record.payeeCode})-${record.supplierType}`
            }
          </span>
        )
      },
      { title: messages('finance-1.key79')/*借款公司*/, dataIndex: 'companyName' },
      {
        title: messages('finance-1.key81')/*借款总额*/, dataIndex: 'loanSum',
        render: (value, record) => (
          <span>
            {record.currencyCode} {this.filterMoney(value, queryCurrencyPrecision(record.currencyCode),true)}
          </span>
        )
      },
      {
        title: messages('finance-1.key334')/*待还款总额*/, dataIndex: 'stayWriteOffSum',
        render: (value, record) => (
          <span style={value === 0 ? { color: '#999' } : { fontWeight: 600, color: '#FF6680' }}>
            {record.currencyCode} {this.filterMoney(value, queryCurrencyPrecision(record.currencyCode), true)}
          </span>
        )
      }
    ]
  );

  columns = [
    {
      title: messages('finance-1.key470')/*借款日期*/, dataIndex: 'createdDate', width: 120,
      render: value => moment(value).format('YYYY-MM-DD')
    },
    {
      title: messages('finance-1.key74')/*借款单号*/, dataIndex: 'businessCode',
      render: (value, record) => <a onClick={e => this.handleRowClick(e, record)}>{value}</a>
    },
    {
      title: messages('finance-1.key80')/*申请人/代理人*/, dataIndex: 'applicantName',
      render: (value,record) => record.submittedBy === record.applicantOid ? value : `${value}/${record.submittedName}`
    },
    {
      title: messages('finance-1.key17')/*借款类型*/, dataIndex: 'loanTypeName'
    },
    {
      title: messages('finance-1.key75')/*事由*/, dataIndex: 'remark',
      render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>
    },
    {
      title: messages('finance-1.key81')/*借款总额*/, dataIndex: 'amount',
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
    },
    {
      title: messages('finance-1.key334')/*待还款总额*/, dataIndex: 'stayWriteOffAmount', sorter: true,
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
    },
    {
      title: messages('common.column.status')/*状态*/, dataIndex: 'status',
      render: value => value === 1006 ? <Badge text={messages('finance-1.key13')/*还款中*/} status="success"/> :
        (value === 1007 ? <Badge text={messages('finance-1.key14')/*已还款*/} status="success"/> : <Badge text={messages('finance-1.key471')/*已付款*/} status="success"/>)
    },
    {
      title: messages('common.operation')/*操作*/, dataIndex: 'operator', render: (value, record) => <div>
        {
          record.stayWriteOffAmount > 0 && !record.creditLocked &&
          this.props.options.repaymentOption.option5 === 'true'
          && <div>
            <a
              onClick={e => this.handleRepayment(e,record)}
              disabled={this.props.currentPageRoute.subFunctions.find(item =>
                item.key === 'loan-global-view').operationType === 'R'}
            >
              {messages('finance-1.key85')/*新建还款*/}
            </a>
          </div>
        }
        {
          record.stayWriteOffAmount > 0 && (
            (record.payeeType === 1001 && ~[1005, 1006].indexOf(record.status)) ||
            (record.payeeType === 1002 && ~[1005, 1006, 1008].indexOf(record.status))
          ) &&
          this.props.options.repaymentOption.option12 === 'true' && (
            <div>
              <a
                onClick={e => this.handleTurn(e,record)}
                disabled={this.props.currentPageRoute.subFunctions.find(item =>
                  item.key === 'loan-global-view').operationType === 'R'}
              >
                {messages('finance-1.key472')/*转交*/}
              </a>
            </div>
          )
        }
        <div>
          <a onClick={e => this.handleViewHistory(e,record)}>{messages('finance-1.key86')/*还款历史*/}</a>
        </div>
      </div>
    }
  ];

  searchForm = [
    {
      id: 'dataRange', label: messages('common.submit.date')/*提交日期*/, component: 'DateRangePicker',
      parser: value => ({
        startDateTime: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endDateTime: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }),
      dataIndex: 'createDate'
    },
    {
      component: 'Input', id: 'businessCodeL', label: messages('finance-1.key74')/*借款单号*/,
      dataIndex: 'businessCode'
    },
    {
      component: 'Input', id: 'employeeKey', label: messages('finance-1.key80')/*申请人/代理人*/,
      props: { placeholder: messages('finance-1.key80')/*申请人/代理人*/ },
      dataIndex: 'applicantName'
    },
    {
      component: 'Input', id: 'title', label: messages('finance-1.key75')/*事由*/,
      dataIndex: 'remark'
    }
  ];

  service = (page, size, searchParams) => {
    const { sort } = this.state;
    if (sort) {
      searchParams.sorts = {
        property: sort.split(',')[0],
        direction: sort.split(',')[1]
      };
    }
    const { payeeId, currencyCode, companyID } = this.props.location.state;
    let temp = { page, size, ...searchParams, payeeId, companyID, currencyCode };
    return httpFetch.post('/api/global/loan/list/v2', temp)
  };

  handleView = record => {
    SlideFrame.open({
      content: ViewLine,
      params: {
        viewId: record.id
      },
      title: messages('finance-1.key45')/*查看借款计划*/
    }, this)
  };

  handleSortChange = (pagination, filter, sorter) => {
    let sort = '';
    if (sorter.order) {
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
    }
    this.setState({ sort }, this.tabRef.getList);
  };

  handleRowClick = (e, record) => {
    e.stopPropagation();
    openSlideFrame.openLoanReport({
      formOID: record.formOid,
      loanBillOID: record.loanBillOid,
      pathname: 'loan-and-refund'
    }, {
      afterClose: value => {typeof value === 'boolean' && value && this.tabRef.getList()}
    }, this);
  };

  handleRepayment = (e, record) => {
    e.stopPropagation();
    this.setState({ editRecord: record });
  };

  handleTurn = (e, record) => {
    e.stopPropagation();
    ListSelector.open({
      type: 'user',
      extraParams: {
        setOfBooksId: record.setOfBooksId
      },
      single: true
    }, this).then(itemList => {
      const { fullName, id } = itemList[0];
      Modal.confirm({
        title: messages('finance-1.key473',{arg1: fullName})/*转交后，该笔借款可由还款人“{arg1}”操作还款、报销。*/,
        onOk: () => {
          this.setState({ tableLoading: true });
          loanAndRefundService.transfer({ payeeId: id, loanLineId: record.id }).then(() => {
            message.success(messages('common.operate.success')/*操作成功*/);
            this.setState({ tableLoading: false }, this.tabRef.getList);
          }).catch(e => {
            this.setState({ tableLoading: false });
            message.error(e.response.data.message);
          })
        }
      })
    })
  };

  handleViewHistory = (e, record) => {
    e.stopPropagation();
    this.setState({ historyId: record.id }, () => this.setState({ historyModal: true }));
  };

  handleViewRefund = item => {
    this.setState({ historyModal: false }, () => {
      if (item.type === '2' || item.type === '3') {
        openSlideFrame.openExpenseReport({
          expenseReportOID: item.expenseReportOid,
          entry: 'view'
        }, {}, this);
      } else {
        SlideFrame.open({
          content: RepaymentDetailFrame,
          params: {
            refundParams: item.repaymentOid,
            pathname: this.props.location.pathname
          },
          title: messages('finance-1.key469')/*还款单详情*/,
          afterClose: value => value && this.tabRef.getList()
        }, this);
      }
    });
  };

  turnToRepay = info => {
    SlideFrame.open({
      content: repaymentContent,
      params: { info, loanRefund: true },
      title: messages('finance-1.key85')/*新建还款*/,
      afterClose: value => {
        this.setState({ editRecord: {} });
        value && this.tabRef.getList();
      }
    }, this);
  };

  render() {
    const { loading, loanInfo, historyModal, historyId, editRecord, tableLoading } = this.state;
    return(
      <div className='full-height-page'>
        <AdvancedTable.SimpleTable
          service={this.service}
          columns={this.columns}
          searchForm={this.searchForm}
          onRef={tabRef => this.tabRef = tabRef}
          rowKey='id'
          onRow={record => ({onClick: () => this.handleView(record)})}
          propsLoading={tableLoading}
          onChange={this.handleSortChange}
        >
          <Info
            attributes={this.attributes(loanInfo)}
            dataSource={loanInfo}
            loading={loading}
          />
        </AdvancedTable.SimpleTable>
        <ViewHistory
          visible={historyModal}
          id={historyId}
          handleViewRefund={this.handleViewRefund}
          close={() => this.setState({historyModal: false})}
        />
        <TransactionModal
          record={editRecord}
          onOK={this.turnToRepay}
        />
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    options: state.login.options,
    currentPageRoute: state.main.currentPageRoute
  }
}

export default SubList
